<!DOCTYPE html>
<html>
<head>
  <title>简单聊天</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" crossorigin="" href="/main.css">
</head>
<body>
<div class="container mt-5">
  <h2>AI Chat Demo</h2>

  <!-- Model Selection -->
  <div class="mb-3">
    <label class="form-label">选择任务类型：</label>
    <div class="btn-group" role="group">
        <span th:each="taskType,i:${taskTypes}">
          <input type="radio" class="btn-check" name="taskType"
                 th:id="${taskType.getCode()}" th:value="${taskType.getCode()}"
                 th:checked="${i.index == 0}"/>
          <label class="btn btn-outline-primary" th:for="${taskType.getCode()}">
              <span th:text="${taskType.getName()}"></span>
          </label>
        </span>
    </div>
  </div>

  <!-- Chat Section -->
  <div class="card mb-4">
    <div class="card-header">
      聊天
    </div>
    <div class="card-body">
      <div class="chat-container" id="chatContainer"></div>
      <div class="input-group">
        <input type="text" class="form-control" id="messageInput" placeholder="输入消息...">
        <button class="btn btn-primary" onclick="sendMessage()">发送</button>
      </div>
    </div>
  </div>

</div>

<script>
  function getTaskType() {
    return document.querySelector('input[name="taskType"]:checked').value;
  }

  function appendMessage(message, isUser) {
    const chatContainer = document.getElementById('chatContainer');
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${isUser ? 'user-message' : 'ai-message'}`;
    messageDiv.textContent = message;
    chatContainer.appendChild(messageDiv);
    chatContainer.scrollTop = chatContainer.scrollHeight;
  }

  async function sendMessage() {
    const messageInput = document.getElementById('messageInput');
    let message = messageInput.value.trim();
    if (!message) {
      message = "你好，你是谁？";
    }

    appendMessage(message, true);
    messageInput.value = '';

    try {
      const response = await fetch('/chat/chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `input=${encodeURIComponent(message)}&taskType=${getTaskType()}`
      });
      const reply = await response.text();
      appendMessage(reply, false);
    } catch (error) {
      console.error('Error:', error);
      appendMessage('发生错误，请稍后重试。', false);
    }
  }

  // 支持按回车发送消息
  document.getElementById('messageInput').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      sendMessage();
    }
  });
</script>
</body>
</html> 